Page({
  data: {
    statusBarHeight: 0,
    fuelRecords: [],
    statistics: {
      totalDistance: 0,
      totalFuel: 0,
      avgConsumption: 0,
      avgCost: 0
    },
    showAddModal: false,
    newRecord: {
      date: '',
      mileage: '',
      fuelAmount: '',
      price: '',
      cost: ''
    },
    inputError: ''
  },

  // 本地存储key
  STORAGE_KEY: 'fuel_calculator_records',

  onLoad: function () {
    // 获取状态栏高度
    const systemInfo = wx.getSystemInfoSync();
    this.setData({
      statusBarHeight: systemInfo.statusBarHeight
    });

    // 设置今天日期
    const today = new Date();
    const year = today.getFullYear();
    const month = String(today.getMonth() + 1).padStart(2, '0');
    const day = String(today.getDate()).padStart(2, '0');

    this.setData({
      'newRecord.date': `${year}-${month}-${day}`
    });

    // 加载本地数据
    this.loadLocalData();
  },

  // 加载本地缓存数据
  loadLocalData: function () {
    try {
      const cachedData = wx.getStorageSync(this.STORAGE_KEY);
      if (cachedData && Array.isArray(cachedData) && cachedData.length > 0) {
        // 加载缓存数据
        this.setData({
          fuelRecords: cachedData
        });
        this.calculateStatistics();
      } else {
        // 没有缓存数据，加载默认真实数据
        this.loadDefaultData();
      }
    } catch (error) {
      console.log('加载缓存数据失败:', error);
      this.loadDefaultData();
    }
  },

  // 加载默认真实数据
  loadDefaultData: function () {
    const realFuelData = []

    this.setData({
      fuelRecords: realFuelData
    });

    // 保存到本地缓存
    this.saveToLocal();
    this.calculateStatistics();
  },

  // 保存数据到本地缓存
  saveToLocal: function () {
    try {
      wx.setStorageSync(this.STORAGE_KEY, this.data.fuelRecords);
    } catch (error) {
      console.log('保存数据到本地失败:', error);
    }
  },

  // 返回上一页
  handleBack: function () {
    wx.navigateBack();
  },

  // 显示添加记录弹窗
  showAddRecord: function () {
    this.setData({
      showAddModal: true,
      newRecord: {
        date: this.data.newRecord.date,  // 保持日期
        mileage: '',
        fuelAmount: '',
        price: '',
        cost: ''
      },
      inputError: ''
    });
  },

  // 关闭添加记录弹窗
  closeAddModal: function () {
    this.setData({
      showAddModal: false
    });
  },

  // 处理输入变化
  onInputChange: function (e) {
    const { field } = e.currentTarget.dataset;
    const value = e.detail.value;

    this.setData({
      [`newRecord.${field}`]: value
    });

    // 如果价格和加油量都有值，自动计算花费
    if (field === 'price' || field === 'fuelAmount') {
      const price = parseFloat(this.data.newRecord.price || 0);
      const fuelAmount = parseFloat(this.data.newRecord.fuelAmount || 0);

      if (price && fuelAmount) {
        const cost = (price * fuelAmount).toFixed(2);
        this.setData({
          'newRecord.cost': cost
        });
      }
    }
  },

  // 添加记录
  addRecord: function () {
    const { mileage, fuelAmount, price, date } = this.data.newRecord;

    // 基本验证
    if (!mileage || !fuelAmount || !price || !date) {
      this.setData({
        inputError: '请填写所有必填字段'
      });
      return;
    }

    // 验证里程必须大于上一条记录
    const records = this.data.fuelRecords;
    if (records.length > 0) {
      const lastMileage = records[records.length - 1].mileage;
      if (parseFloat(mileage) <= lastMileage) {
        this.setData({
          inputError: '里程数必须大于上次记录的里程数'
        });
        return;
      }
    }

    // 计算当前加油效率
    let efficiency = null;
    if (records.length > 0) {
      const lastRecord = records[records.length - 1];
      const distance = parseFloat(mileage) - lastRecord.mileage;
      efficiency = ((parseFloat(fuelAmount) / distance) * 100).toFixed(1);
    }

    // 创建新记录
    const newRecord = {
      id: Date.now(),
      date: date,
      mileage: parseFloat(mileage),
      fuelAmount: parseFloat(fuelAmount),
      price: parseFloat(price),
      cost: parseFloat(this.data.newRecord.cost || (price * fuelAmount).toFixed(2)),
      efficiency: efficiency
    };

    // 添加到记录列表
    const updatedRecords = [...this.data.fuelRecords, newRecord];

    this.setData({
      fuelRecords: updatedRecords,
      showAddModal: false
    });

    // 保存到本地缓存
    this.saveToLocal();

    // 重新计算统计数据
    this.calculateStatistics();

    wx.showToast({
      title: '加油记录已添加',
      icon: 'success'
    });
  },

  // 删除记录
  deleteRecord: function (e) {
    const id = e.currentTarget.dataset.id;

    wx.showModal({
      title: '确认删除',
      content: '确定要删除这条加油记录吗？',
      confirmColor: '#ff6b6b',
      success: (res) => {
        if (res.confirm) {
          const updatedRecords = this.data.fuelRecords.filter(record => record.id !== id);

          this.setData({
            fuelRecords: updatedRecords
          });

          // 保存到本地缓存
          this.saveToLocal();

          this.calculateStatistics();

          wx.showToast({
            title: '记录已删除',
            icon: 'success'
          });
        }
      }
    });
  },

  // 计算统计数据
  calculateStatistics: function () {
    const records = this.data.fuelRecords;

    if (records.length === 0) {
      this.setData({
        statistics: {
          totalDistance: 0,
          totalFuel: '0.0',
          avgConsumption: '0.0',
          avgCost: '0.00'
        }
      });
      return;
    }

    if (records.length === 1) {
      this.setData({
        statistics: {
          totalDistance: 0,
          totalFuel: records[0].fuelAmount.toFixed(1),
          avgConsumption: '0.0',
          avgCost: '0.00'
        }
      });
      return;
    }

    // 计算总距离
    const totalDistance = records[records.length - 1].mileage - records[0].mileage;

    // 计算总油量（除了第一次加油，因为第一次是加满的）
    let totalFuel = 0;
    for (let i = 1; i < records.length; i++) {
      totalFuel += records[i].fuelAmount;
    }

    // 计算总花费
    let totalCost = 0;
    for (let i = 0; i < records.length; i++) {
      totalCost += records[i].cost;
    }

    // 计算平均油耗 (L/100km) - 用实际消耗的油量除以行驶距离
    const avgConsumption = totalDistance > 0 ? (totalFuel / totalDistance * 100).toFixed(1) : '0.0';

    // 计算平均成本 (元/km)
    const avgCost = totalDistance > 0 ? (totalCost / totalDistance).toFixed(2) : '0.00';

    this.setData({
      statistics: {
        totalDistance,
        totalFuel: totalFuel.toFixed(1),
        avgConsumption,
        avgCost
      }
    });
  },

  // 清空本地缓存数据（调试用）
  clearLocalData: function () {
    try {
      wx.removeStorageSync(this.STORAGE_KEY);
      this.setData({
        fuelRecords: [],
        statistics: {
          totalDistance: 0,
          totalFuel: '0.0',
          avgConsumption: '0.0',
          avgCost: '0.00'
        }
      });
      wx.showToast({
        title: '数据已清空',
        icon: 'success'
      });
    } catch (error) {
      console.log('清空数据失败:', error);
    }
  }
}) 